package com.example.demo.service.impl;

import com.example.demo.entity.Account;
import com.example.demo.entity.Company;
import com.example.demo.mapper.AccountMapper;
import com.example.demo.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
@Transactional
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public int createAccount(Account account) {
        // 检查用户名是否已存在
        Account existing = accountMapper.findAccountByUsername(account.getUsername());
        if (existing != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 密码加密
        account.setPassword(encodePassword(account.getPassword()));
        return accountMapper.createAccount(account);
    }

    @Override
    public int deleteAccount(Integer id) {
        return accountMapper.deleteAccount(id);
    }

    @Override
    public Account findAccountByUsername(String username) {
        return accountMapper.findAccountByUsername(username);
    }

    @Override
    public Account findAccountById(Integer id) {
        return accountMapper.findAccountById(id);
    }

    @Override
    public int updateAccount(Account account) {
        if (account.getPassword() != null) {
            account.setPassword(encodePassword(account.getPassword()));
        }
        return accountMapper.updateAccount(account);
    }

    @Override
    public List<Account> findAllAccounts() {
        return accountMapper.findAllAccounts();
    }

    @Override
    public boolean validateAccount(String username, String password) {
        Account account = accountMapper.findAccountByUsername(username);
        if (account == null) {
            return false;
        }
        return checkPassword(password, account.getPassword());
    }

    private String encodePassword(String rawPassword) {
        // 实际项目中应使用BCrypt等加密算法
        return DigestUtils.md5DigestAsHex(rawPassword.getBytes());
    }

    private boolean checkPassword(String rawPassword, String encodedPassword) {
        return encodePassword(rawPassword).equals(encodedPassword);
    }

    @Override
    public Account login(String username, String password) {
        Account account = accountMapper.findAccountByUsername(username);
        if (account == null || !checkPassword(password, account.getPassword())) {
            return null; // 或者抛出异常
        }
        return account;
    }
}
